package com.atguigu.day02;

import com.atguigu.util.IntegerSource;
import com.atguigu.util.IntegerStatistic;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

public class Example7 {
    public static void main(String[] args) {
        var env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        env
                .addSource(new IntegerSource())
                .map(new MapFunction<Integer, IntegerStatistic>() {
                    @Override
                    public IntegerStatistic map(Integer in) throws Exception {
                        return new IntegerStatistic(
                                in,
                                in,
                                in,
                                1,
                                in
                        );
                    }
                })
                .keyBy(r -> "int")
                .reduce(new ReduceFunction<IntegerStatistic>() {
                    @Override
                    public IntegerStatistic reduce(IntegerStatistic acc, IntegerStatistic in) throws Exception {
                        return new IntegerStatistic(
                                Math.max(acc.max, in.max),
                                Math.min(acc.min, in.min),
                                acc.sum + in.sum,
                                acc.count + in.count,
                                (acc.sum + in.sum) / (acc.count + in.count)
                        );
                    }
                })
                .print();

        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
